package azcat.planner.tools;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import azcat.planner.gui.ToolsData;
import azcat.planner.schedule.Schedule;

public class ToolsManager {
	private ArrayList<Tool> neededTools;
	

	private ToolsData data;
	
	public ToolsManager(ToolsData data){
		this.data = data;
		this.neededTools = new ArrayList<Tool>();
	}
	
	public ArrayList<Tool> getNeededTools() {
		return neededTools;
	}

	/**
	 * This method is called by the GUI and will trigger the rest of the calculations
	 */
	public void estimateSchedule(){		
		createNeededToolsList();
		traverseTools();
		NeededToolsEstimator estimator = new NeededToolsEstimator(this.neededTools, data.getMaterials());
		estimator.estimateSchedule();		
	}
	/**
	 * Based on the selected tools from the user, it will create a list of needed tools
	 */
	private void createNeededToolsList(){		
		ArrayList<String> selections = data.getSelections();		
		Tool t;
		//create a new tool and set its name and productivity per hour
		for(int i=0; i< selections.size(); i+=2){			
			t = new Tool();
			t.setName(selections.get(i));//the name of the selected tool
			t.setProductivityPerHour( Integer.parseInt(selections.get(i+1)) );//how many pieces per hour for the tool
			neededTools.add(t);
		}
		
	}
	/**
	 * Just traverse the list of tools
	 */
	private void traverseTools(){		
		for(int i = 0; i< neededTools.size(); i++){			
			getNeededToolsSchedule(neededTools.get(i));
		}
	}
	
	/**
	 * For each generated tool, get the schedule for that tool and add it to the tool
	 * @param tool
	 */
	private void getNeededToolsSchedule(Tool tool){
		String[] info;
		BufferedReader inputStream = null;
		try {
            inputStream = new BufferedReader(new FileReader("Tools.csv"));
            String l;
            while ((l = inputStream.readLine()) != null) {
                info = l.split(",");                
                if(info[1].equals(tool.getName())){  
                	System.out.println(info[0]);
                	Schedule s = new Schedule(info[0]);
                	s.setUsageHours(Integer.parseInt(info[2]));//set how many hour is being used on that day
                	//System.out.println(info[0] + "," +info[1] + "," + info[2]);
                	tool.addSchedule(s);//add the schedule to the tool                	
                	//createMaterialObject(type, info, size);
                }
            }     
            inputStream.close();
		}
		catch(IOException e){	}
		finally {
            if (inputStream != null) {
                try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
		}
	}

}
